package com.wenhua.junshao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wenhua.junshao.common.R;
import com.wenhua.junshao.dot.UserDto;
import com.wenhua.junshao.entity.User;
import com.wenhua.junshao.service.UserService;
import com.wenhua.junshao.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        String phone = user.getPhone();
        //生成4位验证码
        if (StringUtils.isNotEmpty(phone)) {
           String code = "2216";
//            String code  = ValidateCodeUtils.generateValidateCode(4).toString();
            //调用阿里云API服务发送短信
//            SMSUtils.sendMessage("reggie", "", phone, code);
            System.out.println(code);
            //将生成的验证码保存到session中
            redisTemplate.opsForValue().set(phone, code, 100, TimeUnit.SECONDS);
//            request.getSession().setAttribute(phone, code);
            return R.success("成功");

        }

        return R.error("失败");
    }


    /**
     * 发送手机短信验证码
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody UserDto userDto, HttpServletRequest request) {
        String phone = userDto.getPhone();
        String code1 = userDto.getCode();
        //从Redis中获取缓存的验证码
        String code2 = (String) redisTemplate.opsForValue().get(phone);
        if (code1.equals(code2)) {
            //判断手机号是否存在,不存在偷偷注册

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);

            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);

            }
            request.getSession().setAttribute("user", user.getId());

            //从Redis中删除缓存的验证码
            redisTemplate.delete(phone);
            return R.success(user);

        }

        return R.error("登录失败");
    }
}
